package com.lrl.controller;

import com.lrl.pojo.Books;
import com.lrl.service.BookService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    private BookService bookService;
    private List<Books> list;

    @Autowired
    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }

    /*查询书籍信息*/
    @RequestMapping("/allBook")
    public String selectAllBooks(Model model) {
        list = bookService.queryAllBook();
        model.addAttribute("booksList", list);
        return "allBooks";
    }

    /*书籍页面跳转*/
    @RequestMapping("toAddBook")
    public String toAddBookPage(Model model) {
        return "addBook";
    }

    /*增加书籍信息*/
    @RequestMapping("addBook")
    public String addBook(Books book) {
        System.out.println("Controller:addBook:book" + book);
        int nums = bookService.addBook(book);
        System.out.println("Controller:addBook:success nums:" + nums);
        return "redirect:/book/allBook";
    }

    /*跳转进入修改书籍页面*/
    @RequestMapping("toUpdateBook")
    public String toUpdateBookPage(int id, Model model) {
        Books book = bookService.queryBookById(id);
        model.addAttribute("book", book);
        return "updateBook";
    }

    /*修改书籍信息*/
    @RequestMapping("updateBook")
    public String updateBook(Books book) {
        System.out.println("Controller:updateBook:book:" + book);
        int nums = bookService.updateBook(book);
        System.out.println("Controller:updateBook:success nums:" + nums);
        return "redirect:/book/allBook";
    }

    /*修改书籍信息——restFul*/
    @RequestMapping("deleteBook/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
        System.out.println("Controller:deleteBook:deleteId:" + id);
        int nums = bookService.deleteBookById(id);
        System.out.println("Controller:deleteBook:success nums:" + nums);
        return "redirect:/book/allBook";
    }

    /*查询书籍*/
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName, Model model) {
        list = bookService.queryBookByName(queryBookName);
        if (list.size() != 0) {
            model.addAttribute("booksList", list);
            return "allBooks";
        } else {
            model.addAttribute("booksList", bookService.queryAllBook());
            model.addAttribute("error", "无结果");
            return "allBooks";
        }
    }
}
